<?php

namespace addons\TfFutures\backend\controllers;

use addons\RfExample\common\models\Curd as CurdModel;
use addons\TfFutures\common\models\Order as OrderModel;
use common\enums\StatusEnum;
use common\helpers\ExcelHelper;
use common\models\common\SearchModel;
use Yii;
use yii\data\Pagination;
use addons\TfFutures\common\models\Order;
use addons\TfFutures\common\models\OrderReason;
use common\models\common\AuthAssignment;
use common\models\member\Member;
use common\models\sys\Manager;
use common\helpers\ArrayHelper;
use addons\TfFutures\services\OrderService;

class OrderController extends BaseController
{
    public $modelClass = Order::class;
    public $orderClass = OrderReason::class;

    /**
     * 订单管理
     * @return string
     */
    public function actionIndex()
    {
        //time search
        $start_time  = Yii::$app->request->get('start_time');
        $end_time    = Yii::$app->request->get('end_time');
        $type        = Yii::$app->request->get('type');
        $username    = Yii::$app->request->get('username');
        $agentid    = Yii::$app->request->get('agentid');
        $close_type  = Yii::$app->request->get('close_type');

        //代理
        $daili = Manager::find()->select("rf_sys_manager.id,rf_sys_manager.username")->join('LEFT JOIN','rf_common_auth_assignment','rf_sys_manager.id=rf_common_auth_assignment.user_id')->where(["rf_common_auth_assignment.role_id"=>4,"rf_sys_manager.status"=>1])->asArray()->all();
        $daili_id = ArrayHelper::map($daili,"username","id");
        $daili = ArrayHelper::map($daili,"id","username");

        //当前登录id
        $id = Yii::$app->user->id;
        $searchModel = new SearchModel([
            'model'                  => $this->modelClass,
            'scenario'               => 'default',
            'relations'              => ['member_info' => ['username']],
            'partialMatchAttributes' => ['title'], // 模糊查询
            'defaultOrder'           => [
                'open_time' => SORT_DESC,
            ],
            'pageSize'               => $this->pageSize,
        ]);
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        //用户持仓订单
        $order = OrderModel::find()->where(['status' => 1,]);
        //判断当前用户是否为代理
        $daili_type = in_array($id,$daili_id);
    	if(!empty($daili_type)){
    		 //查询此代理下面的用户订单
            $member = Member::find()->where(['daili'=>$id])->select('id,username')->asArray()->all();

            foreach ($member as $item){
                //获取到用户的id
                $member_id[] = $item['id'];
            }
            if (!empty($member_id)) {
                $order = $order->andWhere(['in','member_id',$member_id]);
            }else{
                $order = $order->andWhere(['=','member_id',-1]);
            }
            if(!empty($member_id)){
                $dataProvider->query->andFilterWhere(['in','member_id',$member_id]);
            } else {
                $dataProvider->query->andFilterWhere(['=','member_id',-1]);
            }

    	}
    	$order = $order->select('sum(service_fee) as service_fee, sum(open_price) as open_price, sum(deposit) as deposit, sum(profit) as profit,')->one();
    	//用户名搜索
        if (!empty($username)) {
            $dataProvider->query->andFilterWhere(['like','username',$username]);
        }

        //查询此代理下面的用户
        if (!empty($agentid)) {
            $member = Member::find()->where(['daili'=>$agentid])->select('id,username')->asArray()->all();
            foreach ($member as $item){
                //获取到用户的id
                $member_id[] = $item['id'];
            }
            if(!empty($member_id)){
                $dataProvider->query->andFilterWhere(['in','member_id',$member_id]);
            } else {
                $dataProvider->query->andFilterWhere(['=','member_id','-1']);
            }
            
        }

        if (!empty($type) && $type == 'open_time') {
            $dataProvider->query->andFilterWhere(['between','open_time',$start_time,$end_time]);
        }
        if (!empty($type) && $type == 'close_time'){
            $dataProvider->query->andFilterWhere(['between','close_time',$start_time,$end_time]);
        }

        if (!empty($close_type)) {
            if($close_type == '平仓'){
                $dataProvider->query->andFilterWhere(['state'=>$close_type]);
            }elseif ($close_type == '持仓'){
                $dataProvider->query->andFilterWhere(['state'=>$close_type]);
            }else{
                $dataProvider->query->andFilterWhere(['close_type'=>$close_type]);
            }
        }

		// $dataProvider->query->andFilterWhere(['state'=>"挂单"]);
        return $this->render($this->action->id, [
            'dataProvider' => $dataProvider,
            'searchModel'  => $searchModel,
            'start_time'   => $start_time,
            'end_time'     => $end_time,
            'type'         => $type,
            'close_type'   => $close_type,
            'agentlist'    => $daili,
            'agentid'      => $agentid,
            'daili_type'   => $daili_type,
            'order'        => $order
        ]);
    }
    /**
     * 持仓
     * @return string
     */
    /*public function actionPosition()
    {
        $data   = $this->modelClass::find();
        $pages  = new Pagination(['totalCount' => $data->count(), 'pageSize' => $this->pageSize]);
        $models = $data->offset($pages->offset)
                       ->orderBy('member_id desc')
                       ->limit($pages->limit)
                       ->all();

        return $this->render($this->action->id, [
            'models' => $models,
            'pages'  => $pages,
        ]);
    }*/

    public function actionExcel()
    {
        $model = $this->modelClass::find()
                                  ->where(['>', 'id', 0])
                                  ->all();
        if (empty($model)) {
            return $this->message('没有数据可以被导出', $this->redirect('index'), 'error');
        }
        $header = [
            ['订单ID', 'id', 'text'],
            ['用户名', 'member_info', 'text'],
            ['产品名称', 'symbol_cn', 'text'],
            ['合约量', 'contract_size', 'text'],
            ['开仓时间', 'open_time', 'text'],
            ['开仓价', 'open_price', 'text'],
            ['平仓时间', 'close_time', 'text'],
            ['平仓价', 'close_price', 'text'],
            ['买卖类型', 'rise_fall', 'text'],
            ['手续费', 'service_fee', 'text'],
            ['保证金', 'deposit', 'text'],
            ['盈亏', 'profit', 'text'],
            ['订单状态', 'state', 'text'],
            ['平仓类型', 'close_type', 'text'],
        ];
        foreach ($model as $item) {

            switch ($item->rise_fall) {
                case  'RISE':
                    $rise_fall = '涨';
                    break;
                case  'FALL':
                    $rise_fall = '跌';
                    break;
                default:
                    //123
                    break;
            };
            $list [] = [
                'id'            => $item->id,
                'member_info'   => $item->member_info->username,
                'symbol_cn'     => $item->symbol_cn,
                'contract_size' => $item->contract_size,
                'open_time'     => $item->open_time,
                'open_price'    => $item->open_price,
                'close_time'    => $item->close_time,
                'close_price'   => $item->close_price,
                'close_type'    => $item->close_type,
                'rise_fall'     => $rise_fall,
                'service_fee'   => $item->service_fee,
                'deposit'       => $item->deposit,
                'profit'        => $item->profit,
                'state'         => $item->state,
            ];
        }

        return ExcelHelper::exportData($list, $header);
    }

    //手动平仓
    public function actionAjaxEdit($id){

        $model = OrderService::OrderClose($id,null,"强制平仓",true);
        if($model){
            return $this->message("平仓成功", $this->redirect(['index']), 'success');
        }

    }
}